package com.base.andlanggl.filter

import android.content.Context
import android.opengl.GLES20.*
import android.opengl.Matrix
import com.base.andlangcore.util.LogUtils
import com.base.andlanggl.R
import com.base.andlanggl.objects.Mallet
import com.base.andlanggl.objects.Table
import com.base.andlanggl.programs.ColorShaderProgram
import com.base.andlanggl.programs.TextureShaderProgram
import com.base.andlanggl.util.LangGLTools
import com.base.andlanggl.util.MatrixHelper
import com.base.andlanggl.util.TextureHelper

/**
 * 加入纹理
 */
class QgqGame4(context: Context) {

    private var mContext:Context=context
    //矩阵数据 4*4矩阵
    private var projectionMatrix:FloatArray=FloatArray(16)
    //模型矩阵
    private var modelMatrix:FloatArray=FloatArray(16)

    //桌面
    private var table:Table= Table()
    //木槌
    private var mallet:Mallet=Mallet()
    //纹理着色器
    private lateinit var textureProgram:TextureShaderProgram
    //颜色着色器
    private lateinit var colorProgram:ColorShaderProgram
    //纹理
    private var texture:Int=0

    //初始化
    fun initGame() {
        //设置清空屏幕的色值 红 绿 蓝 alpha
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f)

        //纹理坐标器
        textureProgram=TextureShaderProgram()
        //颜色坐标器
        colorProgram= ColorShaderProgram()

        //加载桌面图片
        texture=TextureHelper.loadTexture(mContext,R.drawable.air_hockey_surface)

    }


    fun drawViewport(width: Int, height: Int){
        //画布宽高左上角 右下角 坐标
        glViewport(0, 0, width, height)

        //使用投影矩阵
        MatrixHelper.perspectiveM(projectionMatrix,45f,width.toFloat()/height.toFloat(),1f,10f)
        //使用模型矩阵
        Matrix.setIdentityM(modelMatrix,0)//设置成单位矩阵
        Matrix.translateM(modelMatrix,0,0f,0f,-2.5f)//将桌子沿着z轴负方向平移-2单位 离得更远些-3
        Matrix.rotateM(modelMatrix,0,-60f,1f,0f,0f)//将桌子沿着x轴旋转-60度
        //投影矩阵*模型矩阵
        var temp:FloatArray=FloatArray(16)//临时变量
        Matrix.multiplyMM(temp,0,projectionMatrix,0,modelMatrix,0)//相乘后赋值
        System.arraycopy(temp,0,projectionMatrix,0,temp.size)//结果复制到projectionMatrix

        LogUtils.d(projectionMatrix.contentToString())
    }

    //绘制
    fun drawGame() {
        //清空屏幕
        glClear(GL_COLOR_BUFFER_BIT)

        //桌子使用纹理着色器
        textureProgram.useProgram()
        textureProgram.setUniforms(projectionMatrix,texture)
        table.bindData(textureProgram)
        table.draw()

        //木槌使用颜色着色器
        colorProgram.useProgram()
        colorProgram.setUniforms(projectionMatrix)
        mallet.bindData(colorProgram)
        mallet.draw()

    }
}